package com.mall.common.domain.manage;

import static com.mall.common.Constants.ROLE_SEPARATOR;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.Table;
import javax.persistence.Transient;

import net.sf.json.JSONObject;

import org.hibernate.validator.constraints.NotBlank;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.mall.common.domain.PriorityEntity;
import com.mall.common.util.PropertiesHelper;

/**
 * 系统模块表
 * @author zhenglong
 */
@Entity
@Table(name="s_menu")
@JsonIgnoreProperties(ignoreUnknown=true) 
public class Menu extends PriorityEntity {
	
	private static final long serialVersionUID = 8607524172042357041L;
	
	public enum MenuType {
		MENUTYPE_PARENT("有子菜单"),
		MENUTYPE_NODE("无子菜单"),
		MENUTYPE_LINE("分割线");
		
		private String name;
		
		private MenuType(String name){
			this.name = name;
		}
		
		public String getTypeName(){
			return this.name;
		}
		
		public String getName(){
			return this.name;
		}
	}
	private String name;//模块名称
	@JsonIgnore private Menu upDomain;//上级模块
	private String description;//描述
	private String menuNo;
	@JsonIgnore private MenuType type;//菜单类别(1:有子菜单，2:无子菜单， 3:分割线)
	@JsonIgnore private Operate operate; //菜单所属动作
	@JsonIgnore private Set<Operate> authOperate; // 授权操作
	@JsonIgnore private Set<Role> roleSet;// 权限
	@JsonIgnore private List<Menu> subMenuList;//子菜单
	
	@Transient
	public boolean getOpen(){
		return this.getId() == null;
	}

	@PrePersist
	public void prePersist(){
		if(this.getPriority() == null){
			this.setPriority(10);
		}
	}
	
	@PreRemove
	public void preremove(){
		List<Menu> children = getSubMenuList();
		if (children != null) {
			for (Iterator<Menu> iterator = children.iterator(); iterator.hasNext(); ){
				Menu menu = iterator.next();
				menu.setUpDomain(null);
			}
		}
		for(Role role : roleSet){
			role.getMenuSet().remove(this);
		}
	}
	
	@Transient
	@JsonIgnore
	public JSONObject getJson(){
		JSONObject obj = new JSONObject();
		obj.put("id", this.getId());
		obj.put("name", this.getName());
		obj.put("type", "menu");
		obj.put("menuNo", this.getMenuNo());
		if(this.getId() == null){
			obj.put("open", true);
		} else {
			obj.put("parentId", this.getParentId());
			//如果是最终菜单，放入操作图标
			if (MenuType.MENUTYPE_NODE.equals(this.getType())){
				obj.put("operateIcon", this.getOperate().getBtnIcon());
				obj.put("html", this.getOperate().getHtml());
				obj.put("mUrl", this.getOperate().getUrl());
			}
		}
		return obj;
	}
	
	// 获取权限字符串（以分隔符间隔）
	@Transient
	@JsonIgnore
	public String getRoleSetString() {
		String system_manager_role = PropertiesHelper.getPropertiesValue("config", "system_manager_role");
		if(this.roleSet == null || this.roleSet.size() == 0) {
			return system_manager_role;
		}
		
		StringBuffer stringBuffer = new StringBuffer();
		for (Role role : this.roleSet) {
			stringBuffer.append(ROLE_SEPARATOR + role.getValue());
		}
		
		//增加系统管理员的权限
		stringBuffer.append(ROLE_SEPARATOR + system_manager_role);
		
		if (stringBuffer.length() > 0) {
			stringBuffer.deleteCharAt(0);
		}
		return stringBuffer.toString();
	}

	@Transient
	public Long getParentId() { 
		Menu parent = getUpDomain();
		if (parent != null) {
			return parent.getId();
		} else {
			return null;
		}
	}
	
	@Transient
	public static Menu genRoot(){
		Menu rootModule = new Menu();
		rootModule.setName("系统根路径");
		rootModule.setType(MenuType.MENUTYPE_PARENT);
		rootModule.setDescription("系统菜单的根对象");
		return rootModule;
	}

	@NotBlank
	@Column(length=20)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="up_id")
	public Menu getUpDomain() {
		return upDomain;
	}

	public void setUpDomain(Menu upDomain) {
		this.upDomain = upDomain;
	}

	@Column(length=255)
	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	@NotBlank 
	public MenuType getType() {
		return type;
	}

	public void setType(MenuType type) {
		this.type = type;
	}

	@OneToOne(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
	@JoinColumn(name="operate_id")
	public Operate getOperate() {
		return operate;
	}

	public void setOperate(Operate operate) {
		this.operate = operate;
	}
	
	@ManyToMany(mappedBy = "menuSet", fetch = FetchType.LAZY)
	public Set<Role> getRoleSet() {
		return roleSet;
	}

	public void setRoleSet(Set<Role> roleSet) {
		this.roleSet = roleSet;
	}
	
	@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.REMOVE)
	@JoinColumn(name = "up_id")
	@OrderBy("priority asc")
	public List<Menu> getSubMenuList() {
		return subMenuList;
	}

	public void setSubMenuList(List<Menu> subMenuList) {
		this.subMenuList = subMenuList;
	}
	
	@OneToMany(mappedBy="menu", cascade=CascadeType.REMOVE)
	@OrderBy("priority asc")
	public Set<Operate> getAuthOperate() {
		return authOperate;
	}

	public void setAuthOperate(Set<Operate> authOperate) {
		this.authOperate = authOperate;
	}

	public String getMenuNo() {
		return menuNo;
	}

	public void setMenuNo(String menuNo) {
		this.menuNo = menuNo;
	}

}